define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');
     
    var shopTable;
    var firstTime = true;
    var totalCount = 0;
    var cityList;
    var cityCode;

    function getOpenCity(code,callback){
        $.ajax({
            type:'POST',
            url:CRM.getOuterUrl('/shop/city/queryOpenCity'),
            contentType:"application/json",  
            data:"{}",
            success:function(data){
                //请求成功
                if(data.status==true){
                    var citystring="";
                    for(var i=0;i<data.entry.length;i++){
                        if(!code){
                            if(i==0){
                                cityCode=data.entry[i].cityCode;
                                citystring += '<option value="'+data.entry[i].cityCode+'" selected>'+data.entry[i].city+'</option>' 
                            }else{
                                citystring += '<option value="'+data.entry[i].cityCode+'">'+data.entry[i].city+'</option>' 
                            }
                        }else{
                            if(code==data.entry[i].cityCode){
                                citystring += '<option value="'+data.entry[i].cityCode+'" selected>'+data.entry[i].city+'</option>' 
                            }else{
                                citystring += '<option value="'+data.entry[i].cityCode+'">'+data.entry[i].city+'</option>' 
                            }
                        }
                    } 
                    callback.call(this);
                    $("#cityselect").html(citystring);
                }
            }
        })
   }

    var deliverFee = {
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "配送费全局设置") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.bindEvent();
            this.initValidator();
            var cityvalue = localStorage.getItem("cityvalue");
            if(cityvalue){
                this.getData(cityvalue);
            }else{
                this.getData();
            }
            
        },
        /**
         * 获取城市列表
         * @param cityCode
         */
        getData:function(code){
            var that = this
            if(code){
               cityCode=code;
            }
            getOpenCity(code,function(){
                  $.ajax({
                    type: "POST",   //请求方式
                    url: CRM.getOuterUrl('/shop/freight/selectRegion'),
                    contentType: "application/json",
                    dataType: "json",   //返回格式为json
                    data:JSON.stringify({
                        "regionCode":cityCode
                    }),   //参数值
                    xhrFields: {
                         withCredentials: true
                     },
                    success: function (req) {
                         var str1 = "",str2 = "";
                         var seeflag = 0;
                         var btnclass = "hide";
                        if(req.status==1){
                            var data = req.entry;
                            if(data.hasLevel){
                               $(".btn.hide").removeClass("hide");
                               btnclass="";
                               $("#functionset").removeClass("hide");
                            }else{
                                $(".btn").addClass("hide");
                                btnclass="hide";
                               $("#functionset").addClass("hide");
                            } 
                            userdeliver = data.deliveryAmount/100;
                            $("#minusinput").attr("data-max",userdeliver);
                           
                            !userdeliver?$("#deliveryAmounttxt").text("0"):$("#deliveryAmounttxt").text(userdeliver);
                            if(data.fullReduceList.length==0){
                                $("#delivertab1 tbody").html('<tr><td width="40%"></td><td>暂无设置</td></tr>')
                            }else{
                                var bigvalue=[];
                                for(var i=0;i<data.fullReduceList.length;i++){
                                    bigvalue.push(data.fullReduceList[i].value/100);                                
                                    str1 += '<tr><td width="40%">满<span>'+data.fullReduceList[i].leastAmount/100+'</span>减<span>'+data.fullReduceList[i].value/100+'</span></td><td><button class="btn btn-info '+btnclass+'" onclick="modifiedSet(\'2\',\'modify\')">修改</button><button class="btn btn-danger '+btnclass+'" onclick="deleteSet(\'2\',\''+data.fullReduceList[i].leastAmount+'\')">删除</button></td></tr>';
                                }
                                var fullbigval = Math.max.apply(null,bigvalue);
                                $("#deliveryAmount").attr("data-min",fullbigval);
                                $("#delivertab1 tbody").html(str1);
                            }
                            if(data.serviceList.length==0){
                                $("#delivertab2 tbody").html('<tr><td width="20%"></td><td width="20%"></td><td>暂无设置</td></tr>')
                            }else{
                                for(var i=0;i<data.serviceList.length;i++){
                                    if(i==0){
                                        str2 += '<tr><td>0<=X<'+data.serviceList[i].leastAmount/100+'</td><td>'+data.serviceList[i].value/100+'%</td><td><button class="btn btn-info '+btnclass+'" onclick="modifiedSet(\'3\',\'modify\')">修改</button><button class="btn btn-danger '+btnclass+'" onclick="deleteSet(\'3\',\''+data.serviceList[i].leastAmount+'\')">删除</button></td></tr>';
                                    }else{
                                        str2 += '<tr><td>'+data.serviceList[i-1].leastAmount/100+'<=X<'+data.serviceList[i].leastAmount/100+'</td><td>'+data.serviceList[i].value/100+'%</td><td><button class="btn btn-info '+btnclass+'" onclick="modifiedSet(\'3\',\'modify\')">修改</button><button class="btn btn-danger '+btnclass+'" onclick="deleteSet(\'3\',\''+data.serviceList[i].leastAmount+'\')">删除</button></td></tr>';
                                    }
                                }
                                $("#delivertab2 tbody").html(str2);
                            }
                        }else{
                             CRM.showDialog(req.message);
                        }
                        
                    },
                    error:function(req){
                        CRM.showDialog(req.message);
                    }
                })
             })
        },
        //添加，修改，删除数据请求接口
        modifyData:function(type,data){
            $.ajax({
                type: "POST",   //请求方式
                url: CRM.getOuterUrl('/shop/freight/addUpdateRegion'),
                contentType: "application/json",
                dataType: "json",   //返回格式为json
                data:data,
                xhrFields: {
                    withCredentials: true
                },
                success: function (req) {
                    if(req.status){
                        CRM.showDialog(req.message); 
                        $("#confirm_dialog").modal("hide");
                        if(type==3){
                            $("#feeset_form3").data('bootstrapValidator').resetForm();
                        }
                        $("#myModal1").modal("hide");
                        setTimeout(function(){
                            $("#confirm_dialog").modal("hide");
                            window.location.reload();
                        },1000);
                    }else{
                       CRM.showDialog(req.message);
                       if($("#confirm_dialog").css("display")=="block"){
                          $("#csonfirm_dialog").modal("hide");
                       } 
                       $("#myModal1").modal("hide");
                        if(type==3){
                            $("#feeset_form3").data('bootstrapValidator').resetForm();
                        }
                    }                
                }
            })
        },
        deleteSet:function(type,value){
            $("#confirm_dialog_content").text("确定要删除这条设置吗");
            $('#confirm_dialog').modal('show');
            $("#comfirm").attr("data-type",type);
            $("#comfirm").attr("data-value",value);
        },
        modifiedSet:function(type,action){
            var that = this;
            $("#deliversetbtn").attr("data-type",type);
            $("#deliversetbtn").attr("data-action",action);
            $("#myModal1").modal("show");
            $("#myModal1 .modal-body div").addClass("hide");
           
            if(type==1){
                $("#myModal1 .modal-header h3").text("向用户收取配送费");
                $("#deliver-input1").removeClass("hide");
                $("#deliver-input1 .form-group").removeClass("hide");
                $("#deliveryAmount").val("");
                $(".error1").text("");
                if($("#form1_check").hasClass("has-error")){
                    $("#form1_check").removeClass("has-error");
                }
                if($("#form1_check").hasClass("has-success")){
                    $("#form1_check").removeClass("has-success");
                }
                if($('#userflag').css("display")=="block"){
                    $('#userflag').hide();
                }
            }
            if(type==2){
                $("#myModal1 .modal-header h3").text("配送费设置");
                $("#deliver-input2").removeClass("hide");
                $("#deliver-input2 .form-group").removeClass("hide");
                $("#fullinput").val("");
                $("#minusinput").val("");
                $(".error2").text("");
                $(".error3").text("");
                if($("#fullset").hasClass("has-error")){
                    $("#fullset").removeClass("has-error");
                }
                if($("#fullset").hasClass("has-success")){
                    $("#fullset").removeClass("has-success");
                }
                if($('#fullflag').css("display")=="block"){
                    $('#fullflag').hide();
                }

                if($("#minusset").hasClass("has-error")){
                    $("#minusset").removeClass("has-error");
                }
                if($("#minusset").hasClass("has-success")){
                    $("#minusset").removeClass("has-success");
                }
                if($('#minusflag').css("display")=="block"){
                    $('#minusflag').hide();
                }
            }
            if(type==3){
                $("#myModal1 .modal-header h3").text("向商户收取配送费");
                $("#deliver-input3").removeClass("hide");
                $("#deliver-input3 .form-group").removeClass("hide");
                $("#excludeinput").val("");
                $("#commissioninput").val("");
                setTimeout(function(){$("#feeset_form3").data('bootstrapValidator').resetForm();},400)
            }
        },
        initValidator: function () {
            $('#feeset_form3').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    excludeinput:{
                       message: '请输入合法数字',
                        validators: {
                          regexp: {
                                regexp: /^[0-9_]+$/,
                                message: '请输入数字'
                        }
                    }   
                    }
                }
            });
        },

        bindEvent: function () {
            var self = this;
            //确认修改用户配送费设置
            $("#userdeliverbtn").click(function(){
                 $("#myModal").modal("hide");
            })
            
            //确认删除操作
            $("#comfirm").click(function(){
                var type = $(this).data("type");
                var value = $(this).data("value");
                var citycode = $("#citySelected").val();
                if(type==2){
                    data = JSON.stringify({
                        "regionCode":cityCode,
                        "delFullReduce":value
                    });
                    self.modifyData("2",data);
                }

                if(type==3){
                    data = JSON.stringify({
                        "regionCode":cityCode,
                        "delService":value
                    });
                    self.modifyData("3",data);
                }
            })

           function check(){
                var check1=false;
                var val = $("#deliveryAmount").val();
                var min = $("#deliveryAmount").attr("data-min");
                var reg = /^[0-9_]+$/;
                if(!val){
                   $(".error1").text("请输入配送费");
                   $("#form1_check").addClass("has-error");
                   $("#userflag").addClass("glyphicon-remove").show();
                   check1=false;
                }else if(!reg.test(val)){
                   $(".error1").text("请输入合法的数字");
                   $("#form1_check").addClass("has-error");
                   $("#userflag").addClass("glyphicon-remove").show();
                   check1=false;
                }else if(val&&min&&parseInt(val)<parseInt(min)){
                   $(".error1").text("满减优惠大于配送费，请先修改满减规则");
                    $("#form1_check").addClass("has-error");
                   $("#userflag").addClass("glyphicon-remove").show();
                   check1=false;
                }else if(val&&min&&parseInt(val)>=parseInt(min)){
                   $(".error1").text("");
                   $("#form1_check").removeClass("has-error").addClass("has-success");
                   $("#userflag").removeClass("glyphicon-remove").addClass("glyphicon-ok").show();
                   check1=true;
                }else{
                  $(".error1").text("");
                  $("#form1_check").removeClass("has-error").addClass("has-success");
                   $("#userflag").removeClass("glyphicon-remove").addClass("glyphicon-ok").show();
                   check1=true;
                }
                return check1;
            }

            function check2(){
                var check2 = false;
                var val = $("#fullinput").val();
                var reg = /^[0-9_]+$/;
                if(!val){
                   check2=false;
                   $(".error2").text("请输入金额");
                   $("#fullset").addClass("has-error");
                   $("#fullflag").addClass("glyphicon-remove").show();
                }else if(!reg.test(val)){
                   check2=false;
                   $(".error2").text("请输入合法数字");
                   $("#fullset").addClass("has-error");
                   $("#fullflag").addClass("glyphicon-remove").show();
                }else{
                   check2=true;
                   $(".error2").text("");
                   $("#fullset").removeClass("has-error").addClass("has-success");
                   $("#fullflag").removeClass("glyphicon-remove").addClass("glyphicon-ok").show();
                }
                return check2;
            }

            function check3(){
                var check3 = false;
                var val = $("#minusinput").val();
                var max = $("#minusinput").attr("data-max");

                var reg = /^[0-9_]+$/;
                if(!val){
                   check3=false;
                   $(".error3").text("请输入金额");
                   $("#minusset").addClass("has-error");
                   $("#minusflag").addClass("glyphicon-remove").show();
                }else if(!reg.test(val)){
                   check3=false;
                   $(".error3").text("请输入合法数字");
                   $("#minusset").addClass("has-error");
                   $("#minusflag").addClass("glyphicon-remove").show();
                }else if(val&&parseInt(val)>parseInt(max)){
                    check3=false;
                   $(".error3").text("输入金额不能大于配送费");
                   $("#minusset").addClass("has-error");
                   $("#minusflag").addClass("glyphicon-remove").show();
                }else if(val&&parseInt(val)<=parseInt(max)){
                   check3=true;
                   $(".error3").text("");
                   $("#minusset").removeClass("has-error").addClass("has-success");
                   $("#minusflag").removeClass("glyphicon-remove").addClass("glyphicon-ok").show();
                }
                return check3;
            }
            

            $("#deliveryAmount").keyup(function(){
                check();
            })

            $("#fullinput").keyup(function(){
               check2();
            })
            $("#minusinput").keyup(function(){
                check3();
            })

            //配送费设置修改
            $("#deliversetbtn").click(function(){
                var type = $(this).attr("data-type");
                var action = $(this).attr("data-action");
                var citycode = $("#citySelected").val();
                //向用户收费修改
                if(type==1){
                    var value = ($("#deliver-input1 input").val())*100;
                    if(check()){
                        data = JSON.stringify({
                            "regionCode":cityCode,
                            "deliveryAmount":value
                        });
                        self.modifyData(type,data);
                    }  
                }
                //配送费设置添加新的收费、或者修改
                if(type==2){
                    var value1 = ($("#fullinput").val())*100;
                    var value2 = ($("#minusinput").val())*100;
                    if(check2() && check3()){
                        data = JSON.stringify({
                            "regionCode":cityCode,
                            "fullReduceLeastAmount":value1,
                            "fullReduceValue":value2
                        });
                        self.modifyData(type,data);
                    }    
                }
                //向商家收取配送费添加新的收费、或者修改
                if(type==3){
                    var value1 = ($("#excludeinput").val())*100;
                    var value2 = ($("#commissioninput").val())*100;
                    $("#feeset_form3").data('bootstrapValidator').resetForm();
                    $("#feeset_form3").data('bootstrapValidator').validate();
                    if($("#feeset_form3").data('bootstrapValidator').isValid()){
                        data = JSON.stringify({
                            "regionCode":cityCode,
                            "serviceLeastAmount":value1,
                            "serviceValue":value2
                        });
                        self.modifyData(type,data);
                    }    
                }
                
            })
            //切换城市
            $("#cityselect").change(function(){
                var citycode= $(this).val();
                localStorage.setItem("cityvalue",citycode);
                self.getData(citycode);
                //window.location.reload();
            })

        }
    };
    window.deleteSet = $.proxy(deliverFee.deleteSet, deliverFee);
    window.addNewSet = $.proxy(deliverFee.addNewSet, deliverFee);
    window.modifiedSet = $.proxy(deliverFee.modifiedSet, deliverFee);
    deliverFee.init();
});